#Get objects
old_ws = ls()

##################################
#Heterogeneous Effects: Seatshare#
##################################

#############
#Tables NVMS#
#############
mergedTable_nvms[, it_seats_district := sum(all_IT_seats) , by = id_kab]
mergedTable_nvms[, seats_district := sum(dapil_seats) , by = id_kab]

useTable_nvms = mergedTable_nvms[!is.na(NVM_Violence_1_count) & (sample_ni_it)]
useTable_nvms[, it_seatshare := (all_IT_seats - IT_win) / (dapil_seats)]
useTable_nvms[, it_seatshare_district := (it_seats_district - IT_win) / (seats_district)]


#constituency islamist seatshare
a = inter.binning(useTable_nvms, Y = "NVM_Violence_1_binary", D = "IT_win", X = "it_seatshare", 
                  main = "NVMS: Any Violence", theme.bw = T)
b = inter.binning(useTable_nvms, Y = "NVM_Violence_1_deaths_binary", D = "IT_win", X = "it_seatshare", 
                  main = "NVMS: Any Deaths", theme.bw = T)

########################
#Tables Violence: PODES#
########################
mergedTable_podes[, it_seats_district := sum(all_IT_seats) , by = id_kab]
mergedTable_podes[, seats_district := sum(dapil_seats) , by = id_kab]

useTable_podes = mergedTable_podes[!is.na(Violence_1_count) & (sample_ni_it)]
useTable_podes[, it_seatshare := (all_IT_seats - IT_win) / (dapil_seats)]
useTable_podes[, it_seatshare_district := (it_seats_district - IT_win) / (seats_district)]

#constituency islamist seatshare
c = inter.binning(useTable_podes, Y = "Violence_1_binary", D = "IT_win", X = "it_seatshare", 
                  main = "PODES: Any Violence", theme.bw = T)
d = inter.binning(useTable_podes, Y = "Violence_1_deaths_binary", D = "IT_win", X = "it_seatshare", 
                  main = "PODES: Any Deaths", theme.bw = T)

#Consituency level islamist seatshare
ylab = "Marginal Effect of Islamist Victory"
xlab = paste("Moderator: Islamist Seatshare (Constituency)")

out_list =  list(c$graph, d$graph, a$graph, b$graph)
for (i in seq_along(out_list)) {
  out_list[[i]]$labels$x = NULL
  out_list[[i]]$labels$y = NULL
  out_list[[i]]$theme$plot.title$size = 15
}

#Generate figure:
out_file = paste0('./output/figures/figure_e3.pdf')
pdf(file = out_file, width = 8.5, height = 8.5)
grid.arrange( 
  arrangeGrob(grobs = out_list, 
              bottom=textGrob(xlab, gp=gpar(fontface="bold", fontsize=15)), 
              left=textGrob(ylab, gp=gpar(fontface="bold", fontsize=15), rot = 90), nrow = 2, ncol = 2) 
)
dev.off()


##################################
#Heterogeneous Effects: Alignment#
##################################

mayors = fread("./data/mayors/mayors_dates_corrected.csv")

#Drop this Kabupaten due to data irregularities
mayors = mayors[kab_code != 3518]

#Drop mayors without known party affiliation
mayors = mayors[!is.na(islamist)]

#Generate term dates: starting 2 months after election date; concluding 5 years after term start
mayors[, start_date := strptime(Pilkada_Date, "%d-%m-%Y") %>% as.Date %>% `+` (60)]
mayors[, end_date := start_date + (365*5)]

#Create panel of dates within the term
mayors_panel = mayors[!is.na(start_date), list(date = seq.Date(start_date, end_date, by = "day")), by = list(kab_code, islamist, Pilkada_Date)]

#Match term dates to election cycle and podes wave
ec_2004 = seq.Date(as.Date('2004-11-01'), as.Date('2009-04-05'), by = "day")
ec_2009 = seq.Date(as.Date('2009-10-01'), as.Date('2014-04-09'), by = "day")
podes_2008_ed = seq.Date(as.Date('2007-04-24'), as.Date('2008-05-24'), by = "day")
podes_2014_ed = seq.Date(as.Date('2013-04-01'), as.Date('2014-04-30'), by = "day")

mayors_panel[, election_cycle := ifelse(date %in% ec_2004, 2004, ifelse(date %in% ec_2009, 2009, NA))]
mayors_panel[, podes_year := ifelse(date %in% podes_2008_ed, 2004, ifelse(date %in% podes_2014_ed, 2009, NA))]

#Create mayors podes data
#########################
mayors_podes = mayors_panel[!is.na(podes_year) & !is.na(election_cycle), list(kab_code, islamist_mayor = islamist, election_cycle, podes_year)] %>% unique

#Merge in PODES data, keep close election sample, non-missing mayor data
setkey(mergedTable_podes, id_kab, election_cycle)
setkey(mayors_podes, kab_code, election_cycle)

mayors_podes = mayors_podes[mergedTable_podes]
mayors_podes = mayors_podes[(sample_ni_it) & !is.na(islamist_mayor)]

#Create mayors NVMS data
#########################
mayors_nvms = mayors_panel[!is.na(election_cycle), list(kab_code, islamist_mayor = islamist, election_cycle, date)] %>% unique

setkey(mergedTable_nvms_daily, id_kab, date)
setkey(mayors_nvms, kab_code, date)

mayors_nvms = mergedTable_nvms_daily[mayors_nvms]

mayors_nvms = mayors_nvms[!is.na(islamist_mayor), list(sample_ni_it = any(sample_ni_it, na.rm = T),
                                  IT_win = any(IT_win, na.rm = T),
                                  NVM_Violence_1 = sum(NVM_Violence_1, na.rm = T),
                                  NVM_Violence_1_deaths = sum(NVM_Violence_1_deaths, na.rm = T),
                                  islamist_mayor = unique(islamist_mayor)
                                  ), by = list(id_kab, dapil_number, election_cycle)]

mayors_nvms = mayors_nvms[!is.na(dapil_number) & !is.na(election_cycle) & (sample_ni_it)]
mayors_nvms[, NVM_Violence_1_binary := (NVM_Violence_1 > 0)]
mayors_nvms[, NVM_Violence_1_deaths_binary := (NVM_Violence_1_deaths > 0)]


#Heterogeneous Effects Analyses
###############################

#NVMS
a = inter.binning(mayors_nvms, Y = "NVM_Violence_1_binary", D = "IT_win", X = "islamist_mayor", 
                  main = "NVMS: Any Violence", theme.bw = T , cutoffs =  0.5, na.rm = T)
b = inter.binning(mayors_nvms, Y = "NVM_Violence_1_deaths_binary", D = "IT_win", X = "islamist_mayor", 
                  main = "NVMS: Any Deaths", theme.bw = T,na.rm = T, cutoffs =  0.5)

#PODES
c = inter.binning(mayors_podes, Y = "Violence_1_binary", D = "IT_win", X = "islamist_mayor", 
                  main = "PODES: Any Violence", theme.bw = T, cutoffs =  0.5, na.rm = T)
d = inter.binning(mayors_podes, Y = "Violence_1_deaths_binary", D = "IT_win", X = "islamist_mayor", 
                  main = "PODES: Any Deaths", theme.bw = T,na.rm = T, cutoffs =  0.5)



ylab = "Marginal Effect of Islamist Victory"
xlab = paste("Moderator: Islamist-Endorsed Regent")

out_list =  list(c$graph, d$graph, a$graph, b$graph)
for (i in seq_along(out_list)) {
  out_list[[i]]$labels$x = NULL
  out_list[[i]]$labels$y = NULL
  out_list[[i]]$theme$plot.title$size = 15
  out_list[[i]]$layers[[5]] = NULL
}

#Generate figure:
out_file = paste0('./output/figures/figure_e2.pdf')
pdf(file = out_file, width = 8.5, height = 8.5)
grid.arrange( 
  arrangeGrob(grobs = out_list, 
              bottom=textGrob(xlab, gp=gpar(fontface="bold", fontsize=15)), 
              left=textGrob(ylab, gp=gpar(fontface="bold", fontsize=15), rot = 90), nrow = 2, ncol = 2) 
)
dev.off()

#cleanup
rm(list = setdiff(ls(), old_ws))